# 
# Project: Last.sk
# File: toptags.py
# Author: Angel Luis Calvo Ortega
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

from viewhandler import ViewHandler

# Modes
#  0: None
#  1: name
#  2: count

_PRE = '''
<table cellpadding="0" cellspacing="0">
<tr><td><b><i>Top Tags</i></b></td></tr>
<tr><td>
'''
SIZES = ('0', '+1', '+2' , '+3', '+4', '+5')

class TopTagsHandler(ViewHandler):
    def __init__(self):
        ViewHandler.__init__(self)
        self.PRE = _PRE
        self.POST = '</td></tr></table>'
        self.ROW = '<font size="%s">%s </font>'
        self.url = 'http://ws.audioscrobbler.com/1.0/user/%s/tags.xml'
        self.title = 'Top Tags'

    def clear(self):
        ViewHandler.clear(self)
        self.mode = 0
        self.name = ''
        self.count = ''
        self.maxcount = 0
    
    def toString(self):
        string = self.PRE
        for tag in self.rows:
            index = (tag[1]*len(SIZES)) / self.maxcount
            if index == len(SIZES):
                index -= 1
            string += self.ROW % (SIZES[index], tag[0])
        string += self.POST
        return string
    
    # SAX methods
    def startElement(self, name, attributes):
        if name == 'name':
            self.mode = 1
        elif name == 'count':
            self.mode = 2
 
    def characters(self, data):
        if self.mode == 1:
            self.name += data
        elif self.mode == 2:
            self.count += data

    def endElement(self, name):
        self.mode = 0
        if name == 'tag':
            tag = (self.name, int(self.count))
            self.rows.append(tag)
            self.maxcount = max(tag[1], self.maxcount)
            self.name = ''
            self.count = ''
            